import type { SelectOption } from '../../../../components/select/types'
import type {
  BaseStyleConfig,
  IPersonalizationItemConfig,
} from '../../../../types/interfaces'
import type { LoadingThemeType } from './types'
import { Select } from '../../../../components/select'
import { UserPref } from '../../../../lib/abstract'
import { createStandardStyleTag } from '../../../../lib/style_injector'
import {
  LOCAL_STORAGE_KEYS,
  logger,
  SettingsStyleId,
  VALID_RESULT,
} from '../../../../types/constants'
import { SYMBOLS } from '../../../../types/interfaces'
import { LoadingThemeService } from './service'
import { LOADING_THEMES } from './types'

export class LoadingTheme extends UserPref {
  readonly id = 'loading_theme'
  readonly name = 'LoadingTheme'
  readonly styleConfigKey = 'loadingTheme'
  readonly cssProperty = ''
  readonly cssValueSuffix = ''
  private service: LoadingThemeService = LoadingThemeService.getInstance()
  readonly cssStyleId: string = SettingsStyleId.LoadingTheme

  constructor(config: IPersonalizationItemConfig) {
    super(config)
  }

  createComponent(config: BaseStyleConfig, value: string, _mode: string, debouncedSave: (() => void) & {
    flush: () => void
  }): Select {
    const id = this.generateId(config.styleVar)
    const remark = config.remark || ''
    return new Select({
      id,
      selectedValue: value,
      label: '加载动画',
      labelTextPosition: 'left',
      options: this.getLoadingThemeOptions(),
      clearable: true,
      showPlaceholder: true,
      placeholder: '选择动画',
      title: remark,
      onChange: (value: string | undefined) => {
        this.cachedValues.set(id, value || '')
        debouncedSave()
        this.handleSelectChange(value)
      },
    })
  }

  getLoadingThemeOptions(): SelectOption[] {
    return Object.entries(LOADING_THEMES).map(([value, config]) => ({
      label: config.name,
      value: value as LoadingThemeType,
    }))
  }

  handleSelectChange(value: string | undefined): void {
    if (value) {
      logger.info(`[${this.name}] ${SYMBOLS.OTHERS.PALETTE} 加载动画切换为: ${value}`)
      this.service.initLoading(value as LoadingThemeType)
      createStandardStyleTag(`${this.cssStyleId}`, this.service.getLoadingStyles(value as LoadingThemeType), {
        allowEmpty: true,
      })
    }
    else {
      logger.info(`[${this.name}] ${SYMBOLS.OTHERS.CLEAR} 移除加载动画`)
      this.service.removeLoading()
    }
  }

  afterSetStorageValues(value: string): void {
    // 同步加载动画主题到本地存储中
    localStorage.setItem(LOCAL_STORAGE_KEYS.LoadingTheme, value)
  }

  // 由于直接使用的是 select 传递的值，所以不需要额外的校验逻辑（支持为空）
  handleCheck(_value: string): { status: ValidResultType, error: string } {
    return { status: VALID_RESULT.VALID.value, error: '' }
  }

  applyStyles(): void {}
}
